local skynet = require "skynet"
local cluster = require "skynet.cluster"
local base = require "base"
local configdao = require "configdao"
local filelog = require "filelog"
local tabletool = require "tabletool"
local timetool = require "timetool"
local timer = require "timer"
local qhbtool = require "qhbtool"
local filename = "tablelogic.lua"
local json = require "cjson"
json.encode_sparse_array(true,1,1)

require "hbslenum"

local server = nil
local tablelogic = {}

function tablelogic.init(service)
	if server == nil then server = service end
end

function tablelogic.init_data(tableobj, conf, node_id)
	if conf == nil or node_id == nil then
		filelog.sys_error(filename .. "conf == nil or node_id == nil ", conf, node_id)
		return 
	end
	tableobj.conf = tabletool.deepcopy(conf)
	local gamelogic = tablelogic.get_gamelogic()
	if gamelogic == nil then
		filelog.sys_error(filename .. "-----table_type-----error-------")
		return
	end
	tableobj.table_index = conf.table_index
	tableobj.svr_id = node_id
	local seatlogic = server:get_logicbyname("seatlogic")
	local seat
	local count = 1
	while count <= conf.max_player_num do
		seat = {
			index = 0,
			rid = 0,
			state = 0,
			agent_address = -1,
			playerinfo = {
				rolename="",
				logo="",
				sex=0,
				ip="",
				adress_gps = 1,
				gps_addr = "",
				ip_address = "",
				diamond = 0,
				fangka = 0,
				coin = 0,
				intro = "",
				upvoted_num = 0,
				downvoted_num = 0,
				logoframe = 0,
			},
			is_robot = false,		--是否是机器人
			next_leave = false,		--
			will_action = 0,
			action_type = 0,
			timer_id = 0,			--定时器
			action_to_time = 0,		--操作超时时间
			cancel_timerid = -1,	 --解散牌桌定时器
			timeout_count = 0,		---玩家操作超时次数
			win = 0,				---记录玩家这局游戏的输赢
			diamond = 0,			----钻石(又叫元宝,用于元宝场)
			is_disconnected = 0, ----玩家是否断线
			balance_score = 0,	 ----最终结算分数
			is_force_quit = 0,	 ----玩家是否强退
			dealnum = 0, 		 ----玩家中间结算量
			balance_total = 0,	 ----自从进桌以来的总输赢
			is_delay_leave = false,
			already_bury_times = 0,	----已经埋雷的次数(机器人使用)
			no_curbury_round = 0,  ----埋雷后还没轮到自己的轮数
			all_qhb_num = 0,
			all_qhb_money = 0,
			recent_qhb_infos = {},
		}
		seatlogic.initseat(seat, count)
		table.insert( tableobj.seats, seat)
		count = count + 1
	end
	tableobj.gamelogic = {
		tableobj = nil,
		stateevent = {}
	}
	gamelogic.initstate(tableobj.gamelogic, tableobj)
	tableobj.is_can_kick = true
	-- if tableobj.conf.table_type == HBSLTableType.TABLE_TYPE_ZUANSI then
	-- 	if tableobj.delete_table_timer_id == -1 then
	-- 		local noticemsg = {
	-- 			table_index = tableobj.conf.table_index,
	-- 			reason = "tableempty",
	-- 		}
	-- 		tableobj.delete_table_timer_id = timer.settimer(tableobj.conf.timeout*100, "delete_table", noticemsg)
	-- 	end
	-- end
	tableobj.state = HBSLTableState.TABLE_STATE_GAME_START
	gamelogic.run(tableobj.gamelogic)
	return true
end

function tablelogic.resetdata()
	local table_data = server.table_data
	table_data.action_type = 0
	table_data.action_to_time = 0
	table_data.cur_landmineinfo = {}
	table_data.already_qhb_playerinfo = {}
	table_data.one_start_time = 0
	table_data.one_end_time = 0
	table_data.tablerecords = nil
	table_data.conf.curr_round_code = "----"
	table_data.replaylogname = ""
	table_data.table_end_flag = false
	table_data.game_records = nil
end

function tablelogic.getallrids()
	local table_data = server.table_data
	local rids = {}
	for index, seatobj in ipairs(table_data.seats) do
		if seatobj.rid ~= 0 then table.insert(rids, seatobj.rid) end
	end
	return rids
end

function tablelogic.get_gamelogic()
	local table_data = server.table_data
	local gamelogic = nil
	if table_data.conf.table_type == HBSLTableType.TABLE_TYPE_ZUANSI then
		gamelogic = server:get_logicbyname("gamelogic")
	end
	return gamelogic
end

function tablelogic.get_gamename()
	local table_data = server.table_data
	local gamename = "hbsl"
    if table_data.conf.table_type == HBSLTableType.TABLE_TYPE_ZUANSI then
        gamename = gamename .. "_diamond_".. table_data.conf.level_type
    end
    return gamename
end

function tablelogic.create_comment()
	local table_data = server.table_data
    local tradeid = skynet.call(".nodeuuid", "lua", "getuuid")
    local ismatchtable = false
    return {
			table_uuid = table_data.conf.uuid,
			table_tradeid = tradeid, 
			start_time = table_data.one_start_time,
			replay_logname = table_data.replaylogname,
			is_matchtable = ismatchtable,
		}
end


function tablelogic.get_emptyseat_by_index(tableobj, index)
	local seatlogic = server:get_logicbyname("seatlogic")
	if index == nil or index <= 0 or index > tableobj.conf.max_player_num then
		for index, seat in pairs(tableobj.seats) do
			if seatlogic.is_empty(seat) then
				return seat
			end
		end
	else
		local seat = tableobj.seats[index]
		if seatlogic.is_empty(seat) then
			return seat
		end
	end
	return nil
end

function tablelogic.entertable(tableobj, rid, msgbody, playerdata, seat, is_reenter)
	local playerinfo = playerdata.info
	local money = playerdata.money
	seat.rid = rid
	seat.gatesvr_id = "node"
	seat.agent_address = "-1"
	seat.playerinfo.rolename = playerinfo.rolename
	seat.playerinfo.logo = playerinfo.logo
	seat.playerinfo.sex	= playerinfo.sex
	seat.playerinfo.diamond = money.diamond
	seat.playerinfo.coin = money.coin
	seat.playerinfo.fangka = money.fangka
	seat.playerinfo.ip_address = playerdata.ip_addr
	seat.playerinfo.intro = playerinfo.intro
	seat.playerinfo.upvoted_num = playerinfo.upvoted_num
	seat.playerinfo.downvoted_num = playerinfo.downvoted_num
	seat.playerinfo.logoframe = playerinfo.logoframe
	seat.playerinfo.level = playerinfo.level
	seat.playerinfo.gps_addr = playerdata.gps_addr
	seat.state = HBSLSeatState.SEAT_STATE_PLAYING
	seat.diamond = money.diamond
	if not is_reenter then 
		tableobj.sitdown_player_num = tableobj.sitdown_player_num + 1
		tableobj.conf.cur_player_num = tableobj.conf.cur_player_num + 1	
	end
end

function tablelogic.copy_tablegameinfo(game_info, rid)
	local table_data = server.table_data
	--[[
	message table_gameinfo {
		optional table_conf 		tableconf 			= 1;
		optional table_baseinfo  	tablebaseinfo 		= 2;
		optional bury_landmineinfo 	burylandmineinfo 	= 3;		//当前可以抢的红包（一般模式用）
		repeated seat_roleinfo 		seatroleinfos 		= 4; 		//抢红包的玩家的信息
		repeated seat_gameinfo 		seatgameinfos 		= 5; 		//抢红包的玩家信息
		optional seat_roleinfo		selfroleinfo 		= 6;  		// 玩家自己的信息	
		optional seat_gameinfo 		selfgameinfo 		= 7;  		// 玩家自己的信息
		optional todo_info			todoinfo       		= 8; 		//
		repeated bury_landmineinfo	can_gethbsinfo		= 9;		//可以抢的红包（无限模式用，有多个红包）
		repeated get_hb_num_list   	hb_num_lists 		= 10; 		// 枪红包数量排行 (无限模式使用)
		repeated get_hb_money_list  hb_money_lists 		= 11; 		// 抢红包金额排行 (无限模式使用)
	}
	--]]
	local table_conf = game_info.tableconf
	tablelogic.copy_table_conf(table_conf)
	local table_baseinfo = game_info.tablebaseinfo
	tablelogic.copy_table_baseinfo(table_baseinfo)

	local bury_landmineinfo = game_info.burylandmineinfo
	tablelogic.copy_bury_landmineinfo(bury_landmineinfo)
	
	local seat_baseinfos = game_info.seatroleinfos
	local seat_playerinfos = game_info.seatgameinfos
	---copy 已经抢红包的玩家
	for index, already_qhb in ipairs(table_data.already_qhb_playerinfo) do
		local qhb_seat = tablelogic.get_seat_by_rid(table_data, already_qhb.rid)
		if qhb_seat then
			local base_roleinfo = {}
			tablelogic.copy_roleinfo(base_roleinfo, qhb_seat)
			local base_gameinfo = {}
			tablelogic.copy_gameinfo(base_gameinfo, qhb_seat)
			table.insert(seat_baseinfos, base_roleinfo)
			table.insert(seat_playerinfos, base_gameinfo)
		end
	end
	
	local self_selfroleinfo = game_info.selfroleinfo
	local self_selfgameinfo = game_info.selfgameinfo
	local todo_info = game_info.todoinfo
	local seat = tablelogic.get_seat_by_rid(table_data, rid)
	if seat then
		tablelogic.copy_roleinfo(self_selfroleinfo, seat)
		tablelogic.copy_gameinfo(self_selfgameinfo, seat)
		local now_time = timetool.get_time()
		if table_data.action_to_time > now_time then
        	todo_info.rid = seat.rid
        	todo_info.action_to_time = table_data.action_to_time
        	todo_info.action_type = table_data.action_type
		end
	end
	if table_data.conf.play_game_type == HBSLPlayGameType.GMAE_TYPE_UNLIMIT then
		for index, can_qiang_landmineinfo in ipairs(table_data.can_qiang_landmineinfos) do
			local base_landmineinfo = {
				hb_id = can_qiang_landmineinfo.hb_id,
				rid = can_qiang_landmineinfo.rid,
				rolename = can_qiang_landmineinfo.rolename,
				logo = can_qiang_landmineinfo.logo,
				sex = can_qiang_landmineinfo.sex,
				total_money = can_qiang_landmineinfo.total_money,
				left_hb_num = can_qiang_landmineinfo.total_hb_num - can_qiang_landmineinfo.already_qhb_num,
				all_hb_num = can_qiang_landmineinfo.total_hb_num,
				landmine_num = can_qiang_landmineinfo.landmine_num,
				times = can_qiang_landmineinfo.times,
				get_money = 0,
				qiang_hb_players = {},
				add_qhb_players = {},
			}
			local already_qhb_playerinfo = table_data.already_qiang_landmineinfos[can_qiang_landmineinfo.hb_id]
			if already_qhb_playerinfo then
				for index, already_qhb in ipairs(already_qhb_playerinfo) do
					local base_data = {
						rid = already_qhb.rid,
						index = already_qhb.get_hb_index,
						qiang_hb_money = already_qhb.qiang_hb_money,
						is_landmine = already_qhb.is_landmine,
						get_hb_money = already_qhb.get_hb_money,
						balance_money = already_qhb.balance_money,
					}
					table.insert(base_landmineinfo.qiang_hb_players, base_data)
				end
			end
			table.insert(game_info.can_gethbsinfo, base_landmineinfo)
		end
		for index, hb_num_rank in ipairs(table_data.qhb_num_rank_lists) do
			local base_data = {
				index = index,
				rid = hb_num_rank.rid,
				rolename = hb_num_rank.rolename,
				logo = hb_num_rank.logo,
				get_hb_num = hb_num_rank.get_hb_num,
			}
			table.insert(game_info.hb_num_lists, base_data)
		end
		--[[
			//抢红包金额排行
			message get_hb_money_list {
				optional int32 	index 			= 1;     // 排名序号
				optional int32 	rid   			= 2; 	  // 玩家rid
				optional string rolename 		= 3;	// 玩家名字
				optional string logo        	= 4;    // 玩家头像
				optional int32  get_hb_money  	= 5; 	// 抢红包金额
			}
		--]]
		for index, hb_money_rank in ipairs(table_data.qhb_money_rank_lists) do
			local base_data = {
				index = index,
				rid = hb_money_rank.rid,
				rolename = hb_money_rank.rolename,
				logo = hb_money_rank.logo,
				get_hb_money = hb_money_rank.get_hb_money,
			}
			table.insert(game_info.hb_money_lists, base_data)
		end
	end
end

function tablelogic.get_seat_by_rid(tableobj, rid)
	for index, seat in pairs(tableobj.seats) do
		if rid == seat.rid then
			return seat
		end
	end
	return nil
end

function tablelogic.copy_table_conf(table_conf)
	--[[
	//创建桌子，桌子的配置，返回桌子配置信息
	message table_conf {
		optional int32	table_type		 	= 1;			//桌子类型
		//通用设置	
		optional int32 	max_player_num	 	= 2;			//桌子支持最大玩家数（旁观的不算）默认12人
		optional int32	is_public		 	= 3;			//是否公开，列表里可以看见（1:公开，0：私密好友）
		optional int32	min_hb_amount    	= 4;			//最小发红包金额
		optional int32	max_hb_amount 	 	= 5;			//最大发红包金额
		optional int32  hb_nums 	 		= 6;			//红包数量
		optional int32	times			 	= 7; 			//倍数
	}
	--]]
	local table_data = server.table_data
	table_conf.table_type = table_data.conf.table_type
	table_conf.max_player_num = table_data.conf.max_player_num
	table_conf.is_public = 1
	table_conf.min_hb_amount = table_data.conf.min_hb_amount
	table_conf.max_hb_amount = table_data.conf.max_hb_amount
	table_conf.hb_nums = table_data.conf.hb_nums
	table_conf.times = table_data.conf.times
end

function tablelogic.copy_table_baseinfo(table_baseinfo)
	--[[
	message table_baseinfo {
		optional int32	table_type			= 1;			//桌子类型
		optional string	uuid				= 2;			//桌子的唯一id，nodename_timenow_code，查看大战绩时也可以使用
		optional int32	index				= 3;			//桌子在table中的序列号 ,这里用的id，就是index
		optional int32	code				= 4;			//随机桌号,客户端也显示成房间号
		optional int32	state				= 5;			//table 状态（准备， 玩牌）
		optional int32	create_rid			= 6;			//创建者rid
		optional string	create_rolename 	= 7;			//创建者姓名
		optional int32	create_time			= 8;			//桌子的创建时间
		optional int32	sitdown_player_num	= 9;			//当前坐在位置上人数
		optional int32  hb_nums 	 		= 10;			//红包数量
		optional int32	times			 	= 11; 			//倍数
		optional int32  sort_type 			= 12;			//排序方式(1按先后排序 2按金额排序(大包优先))
		optional int32  play_game_type		= 13; 			//模式(1 普通模式 2 无限乱斗)
	}
	--]]
	local table_data = server.table_data
	table_baseinfo.table_type = table_data.conf.table_type
	table_baseinfo.uuid = table_data.conf.uuid
	table_baseinfo.index = table_data.conf.table_index
	table_baseinfo.code = table_data.conf.create_table_id
	table_baseinfo.state = table_data.state
	table_baseinfo.create_rid = table_data.conf.create_user_rid
	table_baseinfo.create_rolename = table_data.conf.create_user_rolename
	table_baseinfo.create_time = table_data.conf.create_time
	table_baseinfo.sitdown_player_num = table_data.sitdown_player_num
	table_baseinfo.hb_nums = table_data.conf.hb_nums
	table_baseinfo.times = table_data.conf.times
	table_baseinfo.sort_type = table_data.conf.sort_type
	if table_data.conf.play_game_type == HBSLPlayGameType.GMAE_TYPE_UNLIMIT then
		table_baseinfo.sort_type = 1
	end
	table_baseinfo.play_game_type = table_data.conf.play_game_type or 1
end

function tablelogic.copy_bury_landmineinfo(bury_landmineinfo, bury_get_money)
	--[[
		// 埋雷信息(发红包的相关信息)
	message bury_landmineinfo {
		optional int32 	rid 				= 1;  			// 发红包玩家rid
		optional string rolename 			= 2; 			// 发红包玩家名字
		optional string logo 				= 3; 			//发红包玩家头像
		optional int32 	sex 				= 4; 
		optional int32 	total_money 		= 5; 			// 红包总金额
		optional int32 	left_hb_num 		= 6; 			// 剩余红包数
		optional int32 	landmine_num 		= 7; 			// 雷号
		optional int32 	times 				= 8;			// 倍数
		optional int32	get_money      		= 9;			// 获利多少(结算时使用)
	}
	--]]
	local table_data = server.table_data
	if next(table_data.cur_landmineinfo) == nil then return end
	local landmineinfo = table_data.cur_landmineinfo
	bury_landmineinfo.rid 		= landmineinfo.rid
	bury_landmineinfo.rolename  = landmineinfo.rolename
	bury_landmineinfo.logo      = landmineinfo.logo
	bury_landmineinfo.sex       = landmineinfo.sex
	bury_landmineinfo.total_money = landmineinfo.total_money
	bury_landmineinfo.left_hb_num = landmineinfo.total_hb_num - landmineinfo.already_qhb_num
	bury_landmineinfo.landmine_num = landmineinfo.landmine_num
	bury_landmineinfo.times			= 1
	bury_landmineinfo.get_money     = bury_get_money or 0 
end

function tablelogic.copy_roleinfo(roleinfo, seat, is_playerlist)
	--[[
	//座位玩家基本信息，显示在牌桌上的，不会变的 (抢红包玩家)
	message seat_roleinfo {
		optional int32 rid					= 1;
		optional string rolename 			= 2;
		optional string logo				= 3;
		optional int32 sex					= 4;
		optional int32 diamond				= 5;
		optional string intro    			= 6;			//个人信息
		optional string	ip_addr				= 7;			//登录IP地址
		optional string	gps_addr			= 8;			//玩家位置信息
		optional int32 logoframe    		= 9;			//头像框
	}
	--]]
	roleinfo.rid = seat.rid
	roleinfo.rolename = seat.playerinfo.rolename
	roleinfo.logo = seat.playerinfo.logo
	roleinfo.sex = seat.playerinfo.sex
	roleinfo.diamond = seat.playerinfo.diamond
	if is_playerlist == true then return end
	roleinfo.intro = seat.playerinfo.intro
	roleinfo.ip_addr = seat.playerinfo.ip_addr
	roleinfo.gps_addr = seat.playerinfo.gps_addr
	roleinfo.logoframe = seat.playerinfo.logoframe
end

function tablelogic.copy_gameinfo(gameinfo, seat, is_playerlist)
	--[[
	//座位上和游戏相关的信息，随着游戏的进行，会进行变化的，包括钻石 (抢红包玩家)
	message seat_gameinfo {
		optional int32 rid		   			= 1;
		optional int32 index	   			= 2;			//抢红包先后index
		optional int32 qiang_hb_money   	= 3;			//当前抢到的金额
		optional int32 is_landmine			= 4;			// 是否中雷
		optional int32 get_hb_money			= 5;			// 实际得到的红包的钱(中雷玩家= 抢到的红包金额 - 红包总金额)
		optional int32 balance_money		= 6;			// 实际得到的收益(扣除手续费之后)(只有玩家自己相关的时候才有值)
	}
	--]]
	local table_data = server.table_data
	if is_playerlist == true then return end
	gameinfo.rid = seat.rid
	gameinfo.index = 0
	gameinfo.qiang_hb_money = 0
	gameinfo.is_landmine = 0
	gameinfo.get_hb_money = 0
	gameinfo.balance_money = 0
	local qhb_info = tablelogic.get_qhb_info(seat.rid)
	if qhb_info then
		gameinfo.index = qhb_info.get_hb_index
		gameinfo.qiang_hb_money = qhb_info.qiang_hb_money
		gameinfo.is_landmine = qhb_info.is_landmine
		gameinfo.get_hb_money = qhb_info.get_hb_money
		gameinfo.balance_money = qhb_info.get_hb_money
	end
end

function tablelogic.copy_apply_buryinfo(apply_buryinfo)
	--[[
	// 申请埋雷玩家信息
	message apply_buryinfo {
		optional int32 	apply_id 			= 1; 			//申请序列号(按申请先后顺序排列)
		optional int32 	rid 				= 2; 			// 申请玩家rid
		optional string rolename 			= 3; 			// 申请玩家名字
		optional string logo 				= 4;			//申请玩家头像
		optional int32 	hb_num 				= 5;  			//红包金额
	}
	--]]
	local table_data = server.table_data
	for index, buryinfo in ipairs(table_data.wantbury_landmineinfo) do
		table.insert(apply_buryinfo, 
			{
				apply_id = index,
				rid = buryinfo.rid,
				rolename = buryinfo.rolename,
				logo = buryinfo.logo,
				hb_num = buryinfo.total_money,
			})
	end
end

function tablelogic.get_bury_info_byrid(rid)
	local table_data = server.table_data
	local bury_info = nil
	local bury_key = nil 
	for index, buryinfo in ipairs(table_data.wantbury_landmineinfo) do
		if buryinfo.rid == rid then
			bury_info = buryinfo
			bury_key = index
			break
		end
	end
	return bury_info, bury_key
end

function tablelogic.get_bury_infos_byrid(rid)
	local table_data = server.table_data
	local bury_infos = {}

	for index, buryinfo in ipairs(table_data.wantbury_landmineinfo) do
		if buryinfo.rid == rid then
			table.insert(bury_infos, buryinfo)
		end
	end
	return bury_infos
end

function tablelogic.apply_bury_landmine(rid, seat, msgbody)
	local table_data = server.table_data
	if table_data.conf.play_game_type == HBSLPlayGameType.GAME_TYPE_COMMON then
		local bury_hb_num = msgbody.bury_hb_num or 1
		if bury_hb_num > 0 then
			for i = 1, bury_hb_num do
				local gen_hb_id = skynet.call(".nodeuuid", "lua", "getuuid")
				local base_buryinfo = {
					rid = seat.rid,
					rolename = seat.playerinfo.rolename,
					logo = seat.playerinfo.logo,
					sex = seat.playerinfo.sex,
					total_money = msgbody.hb_total_money,
					total_hb_num = table_data.conf.hb_nums,
					landmine_num = msgbody.landmine_num,
					hb_id = tostring(gen_hb_id),
					times = 1,
				}
				if base_buryinfo.total_hb_num == HBSLBuryHBNums.HB_NUM_SEVEN then
					base_buryinfo.times = 1.5
				end
				table.insert(table_data.wantbury_landmineinfo, base_buryinfo)
			end
		end

		if table_data.conf.sort_type and table_data.conf.sort_type == HBSLBurySortType.BURY_SORT_TYPE_MONEY then
			table.sort(table_data.wantbury_landmineinfo, 
				function(first, second)
					if first.total_money > second.total_money then
						return true
					else
						return false
					end
				end)
		end
	elseif table_data.conf.play_game_type == HBSLPlayGameType.GMAE_TYPE_UNLIMIT then
		local bury_hb_num = msgbody.bury_hb_num
		local hb_total_money = msgbody.hb_total_money
		local want_hb_num = msgbody.hb_nums
		if bury_hb_num > 0 then
			for i = 1, bury_hb_num do
				local gen_hb_id = skynet.call(".nodeuuid", "lua", "getuuid")
				local base_buryinfo = {
					rid = seat.rid,
					rolename = seat.playerinfo.rolename,
					logo = seat.playerinfo.logo,
					sex = seat.playerinfo.sex,
					total_money = hb_total_money,
					total_hb_num = want_hb_num,
					landmine_num = msgbody.landmine_num,
					hb_id = tostring(gen_hb_id),
					times = 1,
				}
				if base_buryinfo.total_hb_num == HBSLBuryHBNums.HB_NUM_SEVEN then
					base_buryinfo.times = 1.5
				end
				table.insert(table_data.wantbury_landmineinfo, base_buryinfo)
			end
		end
	end

	if table_data.state == HBSLTableState.TABLE_STATE_WAIT_PLAYER_BURY_LANDMINE then
		if table_data.conf.play_game_type == HBSLPlayGameType.GAME_TYPE_COMMON then
			local recent_buryinfo = tablelogic.get_online_bury()
			if recent_buryinfo then
				table_data.cur_landmineinfo = {}
				table_data.cur_landmineinfo.rid 			= recent_buryinfo.rid
				table_data.cur_landmineinfo.rolename 		= recent_buryinfo.rolename
				table_data.cur_landmineinfo.logo 			= recent_buryinfo.logo
				table_data.cur_landmineinfo.sex  			= recent_buryinfo.sex
				table_data.cur_landmineinfo.total_money 	= recent_buryinfo.total_money
				table_data.cur_landmineinfo.total_hb_num 	= recent_buryinfo.total_hb_num
				table_data.cur_landmineinfo.landmine_num 	= recent_buryinfo.landmine_num
				table_data.cur_landmineinfo.hb_id 		 	= recent_buryinfo.hb_id
				table_data.cur_landmineinfo.already_qhb_num = 0
				-- table_data.cur_landmineinfo.wait_qhbinfos = qhbtool.gen_all_hbinfos(table_data.cur_landmineinfo.total_money, 
				-- 	table_data.cur_landmineinfo.total_hb_num, 1, math.floor(table_data.cur_landmineinfo.total_money * 3 /10))
				local get_leinum = skynet.call(".slotmgr", "lua", "get_leinum_nums", table_data.cur_landmineinfo.total_hb_num)
				---filelog.sys_error("------get_leinum--------", get_leinum)
				local min_hb_money = base.get_random(18,27)
				local real_min_money = math.floor(table_data.cur_landmineinfo.total_money/100)
				if real_min_money > min_hb_money then
					min_hb_money = real_min_money
				end
				----testcode---
				-- local qian_san_da = 0
				-- for i = 1, 10000 do
				-- 	local get_hbinfos = qhbtool.gen_all_hbinfos_bylandnum(table_data.cur_landmineinfo.total_money, 
				-- 	table_data.cur_landmineinfo.total_hb_num, min_hb_money, math.floor(table_data.cur_landmineinfo.total_money * 2 /table_data.cur_landmineinfo.total_hb_num), 
				-- 		table_data.cur_landmineinfo.landmine_num, get_leinum, get_leinum)
				-- 	local qians_num = 0
				-- 	for index, hbitem in ipairs(get_hbinfos) do
				-- 		if index <= 3 then
				-- 			qians_num = qians_num + hbitem.get_hb_money
				-- 		end
				-- 	end
				-- 	if qians_num > math.floor(table_data.cur_landmineinfo.total_money/ 2) then
				-- 		qian_san_da = qian_san_da + 1
				-- 	end
				-- end
				-- filelog.sys_error("---------------qian_san_da--------------", qian_san_da)
				table_data.cur_landmineinfo.wait_qhbinfos = qhbtool.gen_all_hbinfos_bylandnum(table_data.cur_landmineinfo.total_money, 
					table_data.cur_landmineinfo.total_hb_num, min_hb_money, math.floor(table_data.cur_landmineinfo.total_money * 2 /table_data.cur_landmineinfo.total_hb_num), 
						table_data.cur_landmineinfo.landmine_num, get_leinum, get_leinum)
				table_data.state = HBSLTableState.TABLE_STATE_ONE_GAME_START
				local gamelogic = tablelogic.get_gamelogic()
				gamelogic.run(table_data.gamelogic)
			end
		elseif table_data.conf.play_game_type == HBSLPlayGameType.GMAE_TYPE_UNLIMIT then
			----检查在可抢红包队列的红包数量
			local gamelogic = tablelogic.get_gamelogic()
			gamelogic.add_newhb_nolimit(table_data.gamelogic)
		end
	end
end

function tablelogic.get_can_qiang_landminenum()
	local table_data = server.table_data
	local can_qiang_landminenum = 0
	for index, can_qiang in ipairs(table_data.can_qiang_landmineinfos) do
		if can_qiang.total_hb_num > can_qiang.already_qhb_num then
			can_qiang_landminenum = can_qiang_landminenum + 1
		end
	end
	return can_qiang_landminenum
end

function tablelogic.check_todoN(rid)
	local table_data = server.table_data
	local now_time = timetool.get_time()
	if table_data.action_to_time > now_time then
		local ntc_seat = tablelogic.get_seat_by_rid(table_data, rid)
		if ntc_seat then
			local todontc = {
        		rid = ntc_seat.rid,
        		action_to_time = table_data.action_to_time,
        		action_type = table_data.action_type,
    		}
    		server:send_notice_to_players({ntc_seat.rid}, "todoN", todontc, nil, nil)
		end
	end
end

function tablelogic.check_player_already_qiang(rid)
	local table_data = server.table_data
	local has_qiang = false
	for index, qianginfo in ipairs(table_data.already_qhb_playerinfo) do
		if rid ~= 0 and qianginfo.rid == rid then has_qiang = true break end
	end
	return has_qiang
end

function tablelogic.check_is_already_qhbnolimit(rid, want_qhb_hb_id)
	local table_data = server.table_data
	local has_qiang = false
	local already_qhb_playerinfo_nolimit = table_data.already_qiang_landmineinfos[want_qhb_hb_id]
	if not already_qhb_playerinfo_nolimit then
		return has_qiang
	end
	for index, qianginfo in ipairs(already_qhb_playerinfo_nolimit) do
		if rid ~= 0 and qianginfo.rid == rid then has_qiang = true break end
	end
	return has_qiang
end

function tablelogic.get_qhb_info(rid)
	local table_data = server.table_data
	local qhb_info = nil 
	if rid == 0 or not rid then return qhb_info end
	for index, qianginfo in ipairs(table_data.already_qhb_playerinfo) do
		if qianginfo.rid == rid then qhb_info = qianginfo break end
	end
	return qhb_info
end

function tablelogic.get_qhb_info_nolimit(hb_id, rid)
	local table_data = server.table_data
	local qhb_info = nil
	local already_qhb_playerinfos = table_data.already_qiang_landmineinfos[hb_id]
	if not already_qhb_playerinfos then return qhb_info end

	for index, qianginfo in ipairs(already_qhb_playerinfos) do
		if qianginfo.rid == rid then qhb_info = qianginfo break end
	end
	return qhb_info
end



function tablelogic.get_left_hb_num()
	local table_data = server.table_data
	local left_hb_num = table_data.cur_landmineinfo.total_hb_num - table_data.cur_landmineinfo.already_qhb_num
	return left_hb_num
end

function tablelogic.get_can_qianghb_nolimit(want_qhb_hb_id)
	local can_qiang_hbinfo = nil
	local table_data = server.table_data
	for index, can_qiang_hb in ipairs(table_data.can_qiang_landmineinfos) do
		if can_qiang_hb.hb_id == want_qhb_hb_id then
			can_qiang_hbinfo = can_qiang_hb
		end
	end
	return can_qiang_hbinfo
end



function tablelogic.qhb_deal(rid, seat, msgbody)
	local is_success = false
	local get_hb_money = 0
	local is_landmine = 2
	local table_data = server.table_data
	local cur_landmineinfo = table_data.cur_landmineinfo
	if cur_landmineinfo.total_hb_num - cur_landmineinfo.already_qhb_num <= 0 or #cur_landmineinfo.wait_qhbinfos == 0 then
		return is_success, get_hb_money, is_landmine
	else
		local hbnum = #cur_landmineinfo.wait_qhbinfos
		local get_index = base.get_random(1, hbnum)
		local get_new_hbinfo = table.remove(cur_landmineinfo.wait_qhbinfos, 1) 
		-- if seat.playerinfo.level == 99 then
		-- 	get_new_hbinfo = table.remove(cur_landmineinfo.wait_qhbinfos, 1)
		-- else
		-- 	get_new_hbinfo = table.remove(cur_landmineinfo.wait_qhbinfos, get_index)
		-- end
		if get_new_hbinfo then
			cur_landmineinfo.already_qhb_num = cur_landmineinfo.already_qhb_num + 1
			local already_qhb_infobase = {
				rid = seat.rid,
				rolename = seat.playerinfo.rolename,
				logo = seat.playerinfo.logo,
				sex = seat.playerinfo.sex,
				level = seat.playerinfo.level,
				get_hb_index = cur_landmineinfo.already_qhb_num,
				---get_hb_index = get_new_hbinfo.index,
				qiang_hb_money = get_new_hbinfo.get_hb_money,
				is_landmine = 2,
				get_hb_money = 0,
				balance_money = 0,
			}
			if get_new_hbinfo.hb_numbers == cur_landmineinfo.landmine_num then
				already_qhb_infobase.is_landmine = 1
				already_qhb_infobase.get_hb_money = already_qhb_infobase.qiang_hb_money - (cur_landmineinfo.total_money * table_data.conf.times)
				is_landmine = 1
			else
				already_qhb_infobase.is_landmine = 2
				already_qhb_infobase.get_hb_money = already_qhb_infobase.qiang_hb_money
			end
			table.insert(table_data.already_qhb_playerinfo, already_qhb_infobase)
			is_success = true
			get_hb_money = already_qhb_infobase.qiang_hb_money
			return is_success, get_hb_money, is_landmine
		else
			return is_success, get_hb_money, is_landmine
		end
	end
end

function tablelogic.qhb_deal_nolimit(rid, seat, msgbody)
	local is_success = false
	local get_hb_money = 0
	local is_landmine = 2
	local table_data = server.table_data
	local want_qhb_id = msgbody.hb_id
	local get_qhb_info = tablelogic.get_can_qianghb_nolimit(want_qhb_id)
	if not get_qhb_info then
		return is_success, get_hb_money, is_landmine
	end
	if get_qhb_info.total_hb_num - get_qhb_info.already_qhb_num <= 0 or #get_qhb_info.wait_qhbinfos == 0 then
		return is_success, get_hb_money, is_landmine
	else
		local hbnum = #get_qhb_info.wait_qhbinfos
		local get_index = base.get_random(1, hbnum)
		local get_new_hbinfo = table.remove(get_qhb_info.wait_qhbinfos, 1) 
		-- if seat.playerinfo.level == 99 then
		-- 	get_new_hbinfo = table.remove(cur_landmineinfo.wait_qhbinfos, 1)
		-- else
		-- 	get_new_hbinfo = table.remove(cur_landmineinfo.wait_qhbinfos, get_index)
		-- end
		if get_new_hbinfo then
			get_qhb_info.already_qhb_num = get_qhb_info.already_qhb_num + 1
			local already_qhb_infobase = {
				rid = seat.rid,
				hb_id = get_qhb_info.hb_id,
				rolename = seat.playerinfo.rolename,
				logo = seat.playerinfo.logo,
				sex = seat.playerinfo.sex,
				level = seat.playerinfo.level,
				get_hb_index = get_qhb_info.already_qhb_num,
				---get_hb_index = get_new_hbinfo.index,
				qiang_hb_money = get_new_hbinfo.get_hb_money,
				is_landmine = 2,
				get_hb_money = 0,
				balance_money = 0,
			}
			if get_new_hbinfo.hb_numbers == get_qhb_info.landmine_num then
				already_qhb_infobase.is_landmine = 1
				already_qhb_infobase.get_hb_money = already_qhb_infobase.qiang_hb_money - (get_qhb_info.total_money * get_qhb_info.times)
				is_landmine = 1
			else
				already_qhb_infobase.is_landmine = 2
				already_qhb_infobase.get_hb_money = already_qhb_infobase.qiang_hb_money
			end
			if table_data.already_qiang_landmineinfos[get_qhb_info.hb_id] == nil then
				table_data.already_qiang_landmineinfos[get_qhb_info.hb_id] = {}
			end
			if table_data.add_already_qhb_infos[get_qhb_info.hb_id] == nil then
				table_data.add_already_qhb_infos[get_qhb_info.hb_id] = {}
			end
			--[[
			//最近抢到的红包
			message lastplayergethb {
				optional int32  index 				= 1;
				optional int32  rid  				= 2; //抢红包玩家rid
				optional int32  hb_index 			= 3; //
				optional int32  hb_total_money 		= 4; // 红包总金额
				optional int32 	hb_nums				= 5; // 红包个数
				optional int32	qiang_hb_money		= 6; // 抢到的金额
				optional int32  get_hb_money   		= 7; // 实际得到的红包的钱
				optional string bury_hb_playername  = 8; // 发红包玩家名字
			}
			--]]
			local base_data = {
				index = #seat.recent_qhb_infos + 1,
				rid = seat.rid,
				hb_index = already_qhb_infobase.get_hb_index,
				hb_total_money = get_qhb_info.total_money,
				hb_nums = get_qhb_info.total_hb_num,
				qiang_hb_money = get_new_hbinfo.get_hb_money,
				get_hb_money = 0,
				bury_hb_playername = get_qhb_info.rolename,
				is_landmine = already_qhb_infobase.is_landmine,
			}
			if #seat.recent_qhb_infos > 10 then
				table.remove(seat.recent_qhb_infos, 1)
			end
			table.insert(seat.recent_qhb_infos, base_data)
			seat.all_qhb_num = seat.all_qhb_num + 1
			seat.all_qhb_money = seat.all_qhb_money + base_data.qiang_hb_money
			local seatinfo = {
				rid = seat.rid,
				rolename = seat.playerinfo.rolename,
				logo = seat.playerinfo.logo,
			}
			tablelogic.update_qhb_num_rank(seat.all_qhb_num, seatinfo)
			tablelogic.update_qhb_money_rank(seat.all_qhb_money, seatinfo)
			table.insert(table_data.already_qiang_landmineinfos[get_qhb_info.hb_id], already_qhb_infobase)
			table.insert(table_data.add_already_qhb_infos[get_qhb_info.hb_id], already_qhb_infobase)
			is_success = true
			get_hb_money = already_qhb_infobase.qiang_hb_money
			return is_success, get_hb_money, is_landmine
		else
			return is_success, get_hb_money, is_landmine
		end
	end
end

function tablelogic.notice_already_qhb_infos()
	local table_data = server.table_data
	--[[
		//有玩家抢红包的通知
	message hbslresultN {
		optional bury_landmineinfo burylandmineinfo 	= 1;
		repeated seat_roleinfo 		seatroleinfos 		= 2; 		//抢红包的玩家的信息
		repeated seat_gameinfo 		seatgameinfos 		= 3; 		//抢红包的玩家信息
	}
	--]]
	local hbslresultNtc = {
		burylandmineinfo = {},
		seatroleinfos = {},
		seatgameinfos = {},
	}
	tablelogic.copy_bury_landmineinfo(hbslresultNtc.burylandmineinfo)
	for index, already_qhb in ipairs(table_data.already_qhb_playerinfo) do
		local qhb_seat = tablelogic.get_seat_by_rid(table_data, already_qhb.rid)
		if qhb_seat then
			local base_roleinfo = {}
			tablelogic.copy_roleinfo(base_roleinfo, qhb_seat)
			local base_gameinfo = {}
			tablelogic.copy_gameinfo(base_gameinfo, qhb_seat)
			table.insert(hbslresultNtc.seatroleinfos, base_roleinfo)
			table.insert(hbslresultNtc.seatgameinfos, base_gameinfo)
		end
	end
	local allrids = tablelogic.getallrids()
	server:send_notice_to_players(allrids, "hbslresultN", hbslresultNtc, nil, nil)
end

function tablelogic.balance()
	local table_data = server.table_data
	local data = {}
	local gamename = tablelogic.get_gamename(table_data)
	local service_fee = skynet.call(".slotmgr", "lua", "get_service_fee_rate", gamename) 
	---filelog.sys_error("----------service_fee------------", service_fee)
	local bury_landmineinfo = table_data.cur_landmineinfo
	local bury_seat = tablelogic.get_seat_by_rid(table_data, bury_landmineinfo.rid)
	if not bury_seat then
		filelog.sys_error("-------------bury_seat---is null----------", bury_landmineinfo)
		return
	end

	if bury_seat then
		local bury_bebanlance = bury_seat.diamond
		bury_seat.balance_score = 0 - bury_landmineinfo.total_money
		if data[bury_landmineinfo.rid] == nil then
			data[bury_landmineinfo.rid] = {
				beginvalue = bury_bebanlance,
				value = 0,
				endvalue = 0,
				rolename = bury_seat.playerinfo.rolename,
				real_change = 0,
				level = bury_seat.playerinfo.level,
			}
		end
	end

	local gamename = tablelogic.get_gamename(table_data)
	local sys_diamond_all_before = skynet.call(".slotmgr", "lua", "get_system_inventory", gamename)
	table_data.game_records.sys_diamond_start = sys_diamond_all_before
	table_data.game_records.qhb_result = {}
	local qhb_results = table_data.game_records.qhb_result
	local zhong_lei_num = 0
	local left_money = 0
	for index, qhb_info in ipairs(table_data.already_qhb_playerinfo) do
		if qhb_info.rid ~= bury_seat.rid then
			local qhb_seat  = tablelogic.get_seat_by_rid(table_data, qhb_info.rid)
			if qhb_seat then
				local bebanlance = qhb_seat.diamond
				if qhb_info.is_landmine == 1 then
					bury_seat.balance_score = bury_seat.balance_score + math.floor(bury_landmineinfo.total_money * table_data.conf.times)
					zhong_lei_num = zhong_lei_num + math.floor(bury_landmineinfo.total_money * table_data.conf.times)
				end
				if qhb_info.get_hb_money > 0 then
					qhb_seat.balance_score = qhb_seat.balance_score + math.floor((1 - 2*service_fee) * qhb_info.get_hb_money) 
				else
					qhb_seat.balance_score = qhb_seat.balance_score + qhb_info.get_hb_money
				end
				if data[qhb_seat.rid] == nil then
					data[qhb_seat.rid] = {
						beginvalue = bebanlance,
						value = qhb_seat.balance_score,
						endvalue = 0,
						rolename = qhb_seat.playerinfo.rolename,
						real_change = 0,
						level = qhb_seat.playerinfo.level,
					}
				end
				data[qhb_seat.rid].real_change = data[qhb_seat.rid].real_change + qhb_info.get_hb_money
				qhb_seat.diamond = qhb_seat.diamond + qhb_seat.balance_score
				qhb_seat.playerinfo.diamond = qhb_seat.playerinfo.diamond + qhb_seat.balance_score
				data[qhb_seat.rid].endvalue = qhb_seat.diamond
				
			end
		else
			left_money = left_money + qhb_info.qiang_hb_money
		end
		if qhb_results[qhb_info.rid] == nil then
			qhb_results[qhb_info.rid] = {}
		end
		qhb_results[qhb_info.rid].rid = qhb_info.rid
		qhb_results[qhb_info.rid].rolename = qhb_info.rolename
		qhb_results[qhb_info.rid].logo = qhb_info.logo
		qhb_results[qhb_info.rid].sex = qhb_info.sex
		qhb_results[qhb_info.rid].level = qhb_info.level
		qhb_results[qhb_info.rid].get_hb_index = qhb_info.get_hb_index
		qhb_results[qhb_info.rid].qiang_hb_money = qhb_info.qiang_hb_money  
		qhb_results[qhb_info.rid].is_landmine = qhb_info.is_landmine
		qhb_results[qhb_info.rid].get_hb_money = qhb_info.get_hb_money
	end
	if #bury_landmineinfo.wait_qhbinfos > 0 then
		for index, wait_qhb in ipairs(bury_landmineinfo.wait_qhbinfos) do
			left_money = left_money + wait_qhb.get_hb_money
		end
	end
	zhong_lei_num = zhong_lei_num + left_money
	bury_seat.balance_score = bury_seat.balance_score + left_money
	if bury_seat.balance_score > 0 then
		data[bury_landmineinfo.rid].real_change = bury_seat.balance_score
		bury_seat.balance_score = math.floor((1 - 2 * service_fee) * bury_seat.balance_score)
		bury_seat.diamond = bury_seat.diamond + bury_seat.balance_score
		bury_seat.playerinfo.diamond = bury_seat.playerinfo.diamond + bury_seat.balance_score
		data[bury_landmineinfo.rid].value = bury_seat.balance_score
		data[bury_landmineinfo.rid].endvalue = bury_seat.diamond
	else
		bury_seat.diamond = bury_seat.diamond + bury_seat.balance_score
		bury_seat.playerinfo.diamond = bury_seat.playerinfo.diamond + bury_seat.balance_score
		data[bury_landmineinfo.rid].value = bury_seat.balance_score
		data[bury_landmineinfo.rid].endvalue = bury_seat.diamond
		data[bury_landmineinfo.rid].real_change = bury_seat.balance_score
	end
	table_data.game_records.user_count = 0
	table_data.game_records.players_balance_list = {}
	local players_balance_lists = table_data.game_records.players_balance_list
	for rid, dataitem in pairs(data) do
		table_data.game_records.user_count = table_data.game_records.user_count + 1
		if dataitem.value >= HBSLSendHorseMap.GET_MONEY_MIN then
			local seat = tablelogic.get_seat_by_rid(table_data, rid)
			if seat and seat.playerinfo.level ~= 99 then
				tablelogic.send_horseracelamp(seat.playerinfo.rolename, dataitem.value / 100)
			end
		end
		if players_balance_lists[rid] == nil then
			players_balance_lists[rid] = {}
		end
		players_balance_lists[rid].rid = rid
		players_balance_lists[rid].beginvalue = dataitem.beginvalue
		players_balance_lists[rid].value = dataitem.value
		players_balance_lists[rid].endvalue = dataitem.endvalue
		players_balance_lists[rid].level = dataitem.level
		players_balance_lists[rid].is_bury = 0
		if rid == bury_seat.rid then
			players_balance_lists[rid].is_bury = 1
		end
		if dataitem.level == 99 then
			skynet.send(".robotmgr", "lua", "robot_balance", rid, dataitem.value, table_data.conf.min_hb_amount)
		end
	end
	--[[
		//结算
	message gamebalanceN {
		optional bury_landmineinfo 	burylandmineinfo 	= 1;
		repeated seat_roleinfo 		seatroleinfos 		= 2; 		//抢红包的玩家的信息
		repeated seat_gameinfo 		seatgameinfos 		= 3; 		//抢红包的玩家信息
		optional seat_roleinfo		selfroleinfo 		= 4;  		// 玩家自己的信息	
		optional seat_gameinfo 		selfgameinfo 		= 5;  		// 玩家自己的信息
	}
	--]]
	local gamebalancentc = {
		burylandmineinfo 	= {},
		seatroleinfos 		= {},
		seatgameinfos 		= {},
		selfroleinfo  		= {},
		selfgameinfo 		= {},
	}
	tablelogic.copy_bury_landmineinfo(gamebalancentc.burylandmineinfo, zhong_lei_num)
	---filelog.sys_error("-------gamebalancentc.burylandmineinfo------", zhong_lei_num, gamebalancentc.burylandmineinfo)
	for index, qhb_info in ipairs(table_data.already_qhb_playerinfo) do
		local qhb_seat = tablelogic.get_seat_by_rid(table_data, qhb_info.rid)
		if qhb_seat then
			local base_roleinfo = {}
			tablelogic.copy_roleinfo(base_roleinfo, qhb_seat)
			local base_gameinfo = {}
			tablelogic.copy_gameinfo(base_gameinfo, qhb_seat)
			table.insert(gamebalancentc.seatroleinfos, base_roleinfo)
			table.insert(gamebalancentc.seatgameinfos, base_gameinfo)
		end
	end

	for index, seat in ipairs(table_data.seats) do
		if seat.rid ~= 0 then
			gamebalancentc.selfroleinfo = {}
			gamebalancentc.selfgameinfo = {}
			tablelogic.copy_roleinfo(gamebalancentc.selfroleinfo, seat)
			gamebalancentc.selfgameinfo.rid = seat.rid
			local qhb_info = tablelogic.get_qhb_info(seat.rid)
			if qhb_info and data[seat.rid] then
				gamebalancentc.selfgameinfo.index = qhb_info.get_hb_index
				gamebalancentc.selfgameinfo.qiang_hb_money = qhb_info.qiang_hb_money
				gamebalancentc.selfgameinfo.is_landmine = qhb_info.is_landmine
				gamebalancentc.selfgameinfo.get_hb_money = qhb_info.get_hb_money
				gamebalancentc.selfgameinfo.balance_money = data[seat.rid].value
			else
				gamebalancentc.selfgameinfo.index = 0
				gamebalancentc.selfgameinfo.qiang_hb_money = 0
				gamebalancentc.selfgameinfo.is_landmine = 0
				gamebalancentc.selfgameinfo.get_hb_money = 0
				gamebalancentc.selfgameinfo.balance_money = 0
			end
			server:send_notice_to_players({seat.rid}, "gamebalanceN", gamebalancentc, nil, nil)
		end
	end

	local comment = tablelogic.create_comment()
	local status, comment = tablelogic.game_balance_diamond(data, comment, bury_landmineinfo.total_money)
	---filelog.sys_error("----------game_balance_diamond------", status, comment, data)	
	if status == false then
		filelog.sys_error("-------game_balance_diamond--failed--data-----", data, comment)
		filelog.sys_error("---------bury_seat---------", bury_seat.rid, bury_seat.balance_score, zhong_lei_num)
		filelog.sys_error("---------table_data.already_qhb_playerinfo----", table_data.already_qhb_playerinfo)
	end
	tablelogic.onegameend_save_tablerecord()
end

---无限模式结算
function tablelogic.nolimit_balance(is_over_landmines)
	local table_data = server.table_data
	local gamename = tablelogic.get_gamename(table_data)
	local service_fee = skynet.call(".slotmgr", "lua", "get_service_fee_rate", gamename) 
	local data = {}
	local all_landmines_total_money = 0
	--[[
	//座位上和游戏相关的信息，随着游戏的进行，会进行变化的，包括钻石 (抢红包玩家)
	message seat_gameinfo {
		optional int32 rid		   			= 1;
		optional int32 index	   			= 2;			//抢红包先后index
		optional int32 qiang_hb_money   	= 3;			//当前抢到的金额
		optional int32 is_landmine			= 4;			// 是否中雷
		optional int32 get_hb_money			= 5;			// 实际得到的红包的钱(中雷玩家= 抢到的红包金额 - 红包总金额)
		optional int32 balance_money		= 6;			// 实际得到的收益(扣除手续费之后)(只有玩家自己相关的时候才有值)
	}

	// 埋雷信息(发红包的相关信息)
	message bury_landmineinfo {
		optional string			hb_id 				= 1; 			//红包id(有多个红包 无限模式 使用)
		optional int32 			rid 				= 2;  			// 发红包玩家rid
		optional string 		rolename 			= 3; 			// 发红包玩家名字
		optional string 		logo 				= 4; 			//发红包玩家头像
		optional int32 			sex 				= 5; 
		optional int32 			total_money 		= 6; 			// 红包总金额
		optional int32 			left_hb_num 		= 7; 			// 剩余红包数
		optional int32			all_hb_num          = 8;            // 红包总个数
		optional int32 			landmine_num 		= 9; 			// 雷号
		optional int32 			times 				= 10;			// 倍数
		optional int32			get_money      		= 11;			// 获利多少(结算时使用)
		repeated seat_gameinfo 	qiang_hb_players 	= 12;			// 抢过该红包的玩家列表(无限模式使用 一般模式不用)
		repeated seat_gameinfo  add_qhb_players		= 13;  			// 抢红包的玩家增量列表(无限模式使用 一般模式不用)
	}
	//抢红包数量排行
	message get_hb_num_list {
		optional int32 	index 		= 1;     // 排名序号
		optional int32 	rid   		= 2; 	  // 玩家rid
		optional string rolename 	= 3;	// 玩家名字
		optional string logo        = 4;    // 玩家头像
		optional int32  get_hb_num  = 5; 	// 抢红包数量
	}

	//抢红包金额排行
	message get_hb_money_list {
		optional int32 	index 			= 1;     // 排名序号
		optional int32 	rid   			= 2; 	  // 玩家rid
		optional string rolename 		= 3;	// 玩家名字
		optional string logo        	= 4;    // 玩家头像
		optional int32  get_hb_money  	= 5; 	// 抢红包金额
	}
		//结算
	// 红包抢完通知(无限模式)
	message hboverN {
		repeated bury_landmineinfo 	over_hbs 			= 1; 		// 结束的红包
		repeated get_hb_num_list   	hb_num_lists 		= 2; 		// 枪红包数量排行
		repeated get_hb_money_list  hb_money_lists 		= 3; 		// 抢红包金额排行
		optional seat_roleinfo		selfroleinfo 		= 4;  		// 玩家自己的信息	
		optional seat_gameinfo 		selfgameinfo 		= 5;  		// 玩家自己的信息
	}
	--]]
	local gamebalancentc = {
		over_hbs 			= {},
		hb_num_lists        = {},
		hb_money_lists 		= {},
		selfroleinfo  		= {},
		selfgameinfo 		= {},
	}
	for index, over_landmine in ipairs(is_over_landmines) do
		data = {}
		over_landmine.one_end_time = timetool.get_time()
		local bury_landmineinfo = over_landmine
		local bury_seat = tablelogic.get_seat_by_rid(table_data, bury_landmineinfo.rid)
		if bury_seat then
			local sys_diamond_start = skynet.call(".slotmgr", "lua", "get_system_inventory", gamename)
			local tablerecord_all = {
				conf = tabletool.deepcopy(table_data.conf),
				one_start_time = bury_landmineinfo.one_start_time,
				one_end_time = bury_landmineinfo.one_end_time,
				user_count = 0,
				sys_diamond_start = sys_diamond_start,
				table_code = table_data.conf.code,
				qhb_result = {},
				players_balance_list = {},
			}
			local bury_bebanlance = bury_seat.diamond
			bury_seat.balance_score = 0 - bury_landmineinfo.total_money
			if data[bury_landmineinfo.rid] == nil then
				data[bury_landmineinfo.rid] = {
					beginvalue = bury_bebanlance,
					value = 0,
					endvalue = 0,
					rolename = bury_seat.playerinfo.rolename,
					real_change = 0,
					level = bury_seat.playerinfo.level,
				}
			end
			local qhb_results = tablerecord_all.qhb_result
			local zhong_lei_num = 0
			local left_money = 0
			local base_burylandmine = {
				hb_id = over_landmine.hb_id,
				rid   = over_landmine.rid,
				rolename = over_landmine.rolename,
				logo 	= over_landmine.logo,
				sex     = over_landmine.sex,
				total_money = over_landmine.total_money,
				left_hb_num = over_landmine.total_hb_num - over_landmine.already_qhb_num,
				all_hb_num  = over_landmine.total_hb_num,
				landmine_num  = over_landmine.landmine_num,
				times 		  = over_landmine.times,
				get_money     = 0,
				qiang_hb_players =  {},
				add_qhb_players  = {},
			}
			local already_qhb_playerinfo = table_data.already_qiang_landmineinfos[bury_landmineinfo.hb_id]
			--filelog.sys_error("------------already_qhb_playerinfo-----------", already_qhb_playerinfo)
			if already_qhb_playerinfo then
				for index, qhb_info in ipairs(already_qhb_playerinfo) do
					if qhb_info.rid ~= bury_seat.rid then
						local qhb_seat  = tablelogic.get_seat_by_rid(table_data, qhb_info.rid)
						if qhb_seat then
							local bebanlance = qhb_seat.diamond
							if qhb_info.is_landmine == 1 then
								bury_seat.balance_score = bury_seat.balance_score + math.floor(bury_landmineinfo.total_money * table_data.conf.times)
								zhong_lei_num = zhong_lei_num + math.floor(bury_landmineinfo.total_money * table_data.conf.times)
							end
							if qhb_info.get_hb_money > 0 then
								qhb_seat.balance_score = qhb_seat.balance_score + math.floor((1 - 2*service_fee) * qhb_info.get_hb_money) 
							else
								qhb_seat.balance_score = qhb_seat.balance_score + qhb_info.get_hb_money
							end
							if data[qhb_seat.rid] == nil then
								data[qhb_seat.rid] = {
									beginvalue = bebanlance,
									value = qhb_seat.balance_score,
									endvalue = 0,
									rolename = qhb_seat.playerinfo.rolename,
									real_change = 0,
									level = qhb_seat.playerinfo.level,
								}
							end
							data[qhb_seat.rid].real_change = data[qhb_seat.rid].real_change + qhb_info.get_hb_money
							qhb_seat.diamond = qhb_seat.diamond + qhb_seat.balance_score
							qhb_seat.playerinfo.diamond = qhb_seat.playerinfo.diamond + qhb_seat.balance_score
							data[qhb_seat.rid].endvalue = qhb_seat.diamond
						end
					else
						left_money = left_money + qhb_info.qiang_hb_money
					end
					
					if qhb_results[qhb_info.rid] == nil then
						qhb_results[qhb_info.rid] = {}
					end
					qhb_results[qhb_info.rid].rid = qhb_info.rid
					qhb_results[qhb_info.rid].rolename = qhb_info.rolename
					qhb_results[qhb_info.rid].logo = qhb_info.logo
					qhb_results[qhb_info.rid].sex = qhb_info.sex
					qhb_results[qhb_info.rid].level = qhb_info.level
					qhb_results[qhb_info.rid].get_hb_index = qhb_info.get_hb_index
					qhb_results[qhb_info.rid].qiang_hb_money = qhb_info.qiang_hb_money  
					qhb_results[qhb_info.rid].is_landmine = qhb_info.is_landmine
					qhb_results[qhb_info.rid].get_hb_money = qhb_info.get_hb_money
					table.insert(base_burylandmine.qiang_hb_players, {
								rid = qhb_info.rid,
								index = index,
								qiang_hb_money = qhb_info.qiang_hb_money,
								is_landmine  = qhb_info.is_landmine,
								get_hb_money = qhb_info.get_hb_money,
								balance_money = 0,
					})

				end
				if #bury_landmineinfo.wait_qhbinfos > 0 then
					for index, wait_qhb in ipairs(bury_landmineinfo.wait_qhbinfos) do
						left_money = left_money + wait_qhb.get_hb_money
					end
				end
				zhong_lei_num = zhong_lei_num + left_money
				base_burylandmine.get_money = base_burylandmine.get_money + zhong_lei_num
				bury_seat.balance_score = bury_seat.balance_score + left_money
				if bury_seat.balance_score > 0 then
					data[bury_landmineinfo.rid].real_change = bury_seat.balance_score
					bury_seat.balance_score = math.floor((1 - 2 * service_fee) * bury_seat.balance_score)
					bury_seat.diamond = bury_seat.diamond + bury_seat.balance_score
					bury_seat.playerinfo.diamond = bury_seat.playerinfo.diamond + bury_seat.balance_score
					data[bury_landmineinfo.rid].value = bury_seat.balance_score
					data[bury_landmineinfo.rid].endvalue = bury_seat.diamond
				else
					bury_seat.diamond = bury_seat.diamond + bury_seat.balance_score
					bury_seat.playerinfo.diamond = bury_seat.playerinfo.diamond + bury_seat.balance_score
					data[bury_landmineinfo.rid].value = bury_seat.balance_score
					data[bury_landmineinfo.rid].endvalue = bury_seat.diamond
					data[bury_landmineinfo.rid].real_change = bury_seat.balance_score
				end
				local players_balance_lists = tablerecord_all.players_balance_list
				for rid, dataitem in pairs(data) do
					tablerecord_all.user_count = tablerecord_all.user_count + 1
					if dataitem.value >= HBSLSendHorseMap.GET_MONEY_MIN then
						local seat = tablelogic.get_seat_by_rid(table_data, rid)
						if seat and seat.playerinfo.level ~= 99 then
							tablelogic.send_horseracelamp(seat.playerinfo.rolename, dataitem.value / 100)
						end
					end
					if players_balance_lists[rid] == nil then
						players_balance_lists[rid] = {}
					end
					players_balance_lists[rid].rid = rid
					players_balance_lists[rid].beginvalue = dataitem.beginvalue
					players_balance_lists[rid].value = dataitem.value
					players_balance_lists[rid].endvalue = dataitem.endvalue
					players_balance_lists[rid].level = dataitem.level
					players_balance_lists[rid].is_bury = 0
					if rid == bury_seat.rid then
						players_balance_lists[rid].is_bury = 1
					end
					if dataitem.level == 99 then
						skynet.send(".robotmgr", "lua", "robot_balance", rid, dataitem.value, table_data.conf.min_hb_amount)
					end
				end
				all_landmines_total_money = all_landmines_total_money + bury_landmineinfo.total_money
				local comment = tablelogic.create_comment()
				local status, comment = tablelogic.game_balance_diamond(data, comment, all_landmines_total_money)
				---filelog.sys_error("-------nolimit------game_balance_diamond------", status, comment, data)	
				if status == false then
					filelog.sys_error("-------game_balance_diamond--failed--data-----", data, comment)
					filelog.sys_error("---------bury_seat---------", bury_seat.rid, bury_seat.balance_score, zhong_lei_num)
					filelog.sys_error("---------table_data.already_qhb_playerinfo----", table_data.already_qhb_playerinfo)
				end
				tablelogic.save_table_records_nolimit(tablerecord_all, bury_landmineinfo)
			end
			table.insert(gamebalancentc.over_hbs, base_burylandmine)
			table_data.already_qiang_landmineinfos[bury_landmineinfo.hb_id] = nil
		end
	end

	for index, rank in ipairs(table_data.qhb_num_rank_lists) do
		table.insert(gamebalancentc.hb_num_lists, {
			index = index,
			rid   = rank.rid,
			rolename = rank.rolename,
			logo  = rank.logo,
			get_hb_num = rank.get_hb_num,
		})
	end

	for index, rank in ipairs(table_data.qhb_money_rank_lists) do
		table.insert(gamebalancentc.hb_money_lists, {
			index = index,
			rid 	= rank.rid,
			rolename = rank.rolename,
			logo 	= rank.logo,
			get_hb_money = rank.get_hb_money,
		})
	end
	--[[
	local players_balance_lists = table_data.game_records.players_balance_list
	for rid, dataitem in pairs(data) do
		table_data.game_records.user_count = table_data.game_records.user_count + 1
		if dataitem.value >= HBSLSendHorseMap.GET_MONEY_MIN then
			local seat = tablelogic.get_seat_by_rid(table_data, rid)
			if seat and seat.playerinfo.level ~= 99 then
				tablelogic.send_horseracelamp(seat.playerinfo.rolename, dataitem.value / 100)
			end
		end
		if players_balance_lists[rid] == nil then
			players_balance_lists[rid] = {}
		end
		players_balance_lists[rid].rid = rid
		players_balance_lists[rid].beginvalue = dataitem.beginvalue
		players_balance_lists[rid].value = dataitem.value
		players_balance_lists[rid].endvalue = dataitem.endvalue
		players_balance_lists[rid].level = dataitem.level
		players_balance_lists[rid].is_bury = 0
		if rid == bury_seat.rid then
			players_balance_lists[rid].is_bury = 1
		end
		if dataitem.level == 99 then
			skynet.send(".robotmgr", "lua", "robot_balance", rid, dataitem.value, table_data.conf.min_hb_amount)
		end
	end
	--]]
	---filelog.sys_error("-------------hb_qiang_wan-------", gamebalancentc)
	for index, seat in ipairs(table_data.seats) do
		if seat.rid ~= 0 then
			gamebalancentc.selfroleinfo = {}
			gamebalancentc.selfgameinfo = {}
			tablelogic.copy_roleinfo(gamebalancentc.selfroleinfo, seat)
			gamebalancentc.selfgameinfo.rid = seat.rid
			local qhb_info = tablelogic.get_qhb_info(seat.rid)
			if qhb_info and data[seat.rid] then
				gamebalancentc.selfgameinfo.index = qhb_info.get_hb_index
				gamebalancentc.selfgameinfo.qiang_hb_money = qhb_info.qiang_hb_money
				gamebalancentc.selfgameinfo.is_landmine = qhb_info.is_landmine
				gamebalancentc.selfgameinfo.get_hb_money = qhb_info.get_hb_money
				gamebalancentc.selfgameinfo.balance_money = data[seat.rid].value
			else
				gamebalancentc.selfgameinfo.index = 0
				gamebalancentc.selfgameinfo.qiang_hb_money = 0
				gamebalancentc.selfgameinfo.is_landmine = 0
				gamebalancentc.selfgameinfo.get_hb_money = 0
				gamebalancentc.selfgameinfo.balance_money = 0
			end
			server:send_notice_to_players({seat.rid}, "hboverN", gamebalancentc, nil, nil)
		end
	end
	---tablelogic.onegameend_save_tablerecord()
end

function tablelogic.game_balance_diamond(data, comment, total_money)
 	local tableobj = server.table_data
 	local sumvalue = 0
 	local real_datas = {}
 	for rid, itemdata in pairs(data) do
 		sumvalue = sumvalue + itemdata.real_change
 		if real_datas[rid] == nil and itemdata.level ~= 99 then
 			real_datas[rid] = {
 				beginvalue = itemdata.beginvalue,
				value = itemdata.value,
				endvalue = itemdata.endvalue,
				rolename = itemdata.rolename,
				real_change = itemdata.real_change,
				level = itemdata.level,
 			}
 		end		
 	end
 	if sumvalue ~= 0 then
 		filelog.sys_error("-----------sumvalue ~= 0-------------", data, comment)
 		return false, comment
 	end

    ---local status, result = skynet.pcall(cluster.call, "gatenode", ".router", "game_balance_diamond", data, comment)
    local status, result = skynet.pcall(cluster.call, "gatenode", ".router", "brgame_balance_diamond", real_datas, comment)
    if not status then
        filelog.sys_error("brgame_balance_diamond call failed!")
        return false
    else
        --记录流水日志
        local total_bet = total_money or 0
        local total_water = 0
        local sys_change = 0
        local total_change = 0
        local robot_num = 0
        for rid,item in pairs(data) do
        	if item.level ~= 99 then
            	--total_water = total_water + math.abs(item.real_change or 0)
                --total_bet = total_bet + (item.total_bet or 0)
            	sys_change = sys_change + item.real_change
            	total_change = total_change + item.value
                --记录下注值
            	local bet_logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", EDiamondChange.DOBET, rid, item.level, 
            	0, 0, 0, 0, 0, 0, comment.table_uuid, comment.start_time, comment.table_tradeid)
            	skynet.send(".diamondlog", "lua", "write", bet_logstr)
                --记录流水变化值
            	local chg_logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", EDiamondChange.FUWUFEI, rid, item.level, item.real_change, 
            	item.beginvalue, item.endvalue, 0, 0, 0, comment.table_uuid, comment.start_time, comment.table_tradeid)
            	if item.real_change ~= 0 then
                	skynet.send(".diamondlog", "lua", "write_file_redis", chg_logstr, rid)
            	else
                	skynet.send(".diamondlog", "lua", "write", chg_logstr)
            	end
            else
            	robot_num = robot_num + 1
            	--total_water = total_water + math.abs(item.real_change or 0)
        	end
        end
        if robot_num == 0 then
        	total_bet = 0
        end

        --记录系统的流水变化
        --filelog.sys_error("----------sys_change-------", sys_change)
        local logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", EDiamondChange.FUWUFEI, 0, 0, -sys_change, 0, 0, 0, 0, 0,
        comment.table_uuid, comment.start_time, comment.table_tradeid)
        skynet.send(".diamondlog", "lua", "write", logstr)

        --更新收益值,库存值，扣除抽水
        local gamename =  tablelogic.get_gamename(tableobj)
        ---filelog.sys_error("--------handle_balance_result---", gamename, total_change, total_water, total_bet, sys_change)
        if robot_num > 0 then
        	skynet.call(".slotmgr", "lua", "handle_balance_result", gamename, total_change, total_water, total_bet, comment, sys_change)
        end
        skynet.pcall(skynet.call,".slotmgr", "lua", "update_system_water_profit", gamename, sys_change - total_change)
    end
    return result,comment
end

function tablelogic.leavetable(rid, seat)
	local table_data = server.table_data
	if table_data.sitdown_player_num > 0 then
		table_data.sitdown_player_num = table_data.sitdown_player_num - 1
	end
	if table_data.conf.cur_player_num > 0 then
		table_data.conf.cur_player_num = table_data.conf.cur_player_num - 1	
	end
	tablelogic.clear_player_from_ranklist(rid)
	local leaveNtc = {
		rid = seat.rid,
	}
	---server:send_notice_to_players(rids, "leavetableN", leaveNtc, nil, nil)
	skynet.call(".router", "lua", "clear_ridinfo", 0, rid, table_data.conf.table_index, table_data.conf.table_type)
	local seatlogic = server:get_logicbyname("seatlogic")
	if seat ~= nil then
		seatlogic.clear_seat(seat)
	end
end

function tablelogic.check_hb_is_qw()
	local table_data = server.table_data
	local tablelogic = server:get_logicbyname("tablelogic")
	local bury_landmineinfo = table_data.cur_landmineinfo
	local all_already_qhbinfo = table_data.already_qhb_playerinfo
	if bury_landmineinfo.already_qhb_num == bury_landmineinfo.total_hb_num  and #all_already_qhbinfo == bury_landmineinfo.already_qhb_num then
		---filelog.sys_error("--------红包抢完--------结算-------------")
		table_data.state = HBSLTableState.TABLE_STATE_ONE_GAME_END
		local gamelogic = tablelogic.get_gamelogic()
		gamelogic.run(table_data.gamelogic)
	end
end

function tablelogic.get_qhb_robot_num()
	local table_data = server.table_data
	local qhb_robot_num = 0
	for index, qhbplayerinfo in pairs(table_data.already_qhb_playerinfo) do
		if qhbplayerinfo.level == 99 then
			qhb_robot_num = qhb_robot_num + 1
		end
	end
	return qhb_robot_num
end

function tablelogic.get_real_playernum()
	local table_data = server.table_data
	local real_playernum = 0
	for index, seat in ipairs(table_data.seats) do
		if seat.rid ~= 0 and seat.playerinfo.level ~= 99 then
			real_playernum = real_playernum + 1
		end
	end
	return real_playernum 
end

function tablelogic.get_qhb_robot_num_nolimit(hb_id)
	local table_data = server.table_data
	local qhb_robot_num = 0
	local already_qhb_playerinfo = table_data.already_qiang_landmineinfos[hb_id]
	if not already_qhb_playerinfo then return qhb_robot_num end
	for index, qhbplayerinfo in pairs(already_qhb_playerinfo) do
		if qhbplayerinfo.level == 99 then
			qhb_robot_num = qhb_robot_num + 1
		end
	end
	return qhb_robot_num
end

function tablelogic.check_player_is_leave()
	local table_data = server.table_data
	for index, seat in ipairs(table_data.seats) do
		if seat.rid ~= 0 and seat.next_leave == true then
			---tablelogic.leavetable(seat.rid, seat)
			tablelogic.passive_standuptable(seat)
		end
	end
end

function tablelogic.send_horseracelamp(rolename, get_num)
	local horseconf = configdao.get_common_conf("horselampconf")
	----filelog.sys_error("----------horseconf--------", rolename, get_num)
	if not horseconf or not horseconf[1] then return end
	local formatname = string.format(HBSLLAMPCOLOR.GREEN, rolename)
	local formatnum = string.format(HBSLLAMPCOLOR.RED, tostring(get_num))
	local horsestring = string.format(horseconf[1], formatname, formatnum)
	local msg = {
		content = horsestring,
	}
	local result = cluster.send("gatenode", ".router", "addpopmessage", msg.content)
end

function tablelogic.onegamestart_init_tablerecord()
    local tableobj = server.table_data
    if tableobj.game_records == nil then
    	tableobj.game_records = {}
    end
    tableobj.game_records.table_type = tableobj.conf.table_type               --桌子类型
	tableobj.game_records.table_uuid = tableobj.conf.uuid                     --桌子uuid
    tableobj.game_records.create_user_rid = tableobj.conf.create_user_rid          --创建者rid
    tableobj.game_records.conf = tableobj.conf or { }                    --桌子配置
    tableobj.game_records.table_code = tableobj.conf.create_table_id                     --桌号
    --每局信息
    tableobj.game_records.cur_record_id = ""                             --本局记录日志id（log日志文件名）
    tableobj.game_records.curr_to_num = tableobj.curr_to_num or 0        --当前局数
    tableobj.game_records.one_start_time = tableobj.one_start_time or 0  --本局开始时间
    tableobj.game_records.one_end_time = 0                               --本局结束时间
    tableobj.game_records.table_tradeid = ""                             --本局唯一交易id
    tableobj.game_records.players_balance_list = {}                      --本局结算情况
    tableobj.game_records.sys_diamond_start = 0                          --系统开始钻石
    tableobj.game_records.sys_diamond_end = 0                            --系统结束钻石
    tableobj.game_records.user_count = 0                                 --游戏总人数
    tableobj.game_records.banker_seat_index = tableobj.banker_seat_index or 0       --庄家位置
    tableobj.game_records.role_info = {}                                           --玩家信息
    tableobj.game_records.qhb_result = {}
end


function tablelogic.onegameend_save_tablerecord()
	local table_data = server.table_data
	local game_records = table_data.game_records
	local record_id = game_records.table_uuid .. "_"
    record_id = record_id .. game_records.one_start_time .. "_"
    record_id = record_id .. game_records.one_end_time .. "_"
    record_id = record_id .. table_data.conf.play_game_type .. "_"
	record_id = record_id .. os.date("%Y%m%d_%H%M%S", game_records.one_start_time)
	game_records.cur_record_id = game_records.cur_record_id .. record_id

end

function tablelogic.save_table_records()
	local table_data = server.table_data
	local game_records = table_data.game_records
	local gamename = tablelogic.get_gamename(table_data)
	local sys_diamond_all_end = skynet.call(".slotmgr", "lua", "get_system_inventory", gamename)
	game_records.sys_diamond_end = sys_diamond_all_end
    if not game_records.user_count or game_records.user_count <= 0 then
        return
    end
    local tablerecordstr =  ""
    tablerecordstr = tablerecordstr .. json.encode(game_records.conf) .. "\n"
    local tablerecords = {}
    tablerecords.user_count = game_records.user_count                       --游戏总人数
    tablerecords.sys_diamond_start = game_records.sys_diamond_start         --系统开始元宝
    tablerecords.sys_diamond_end = game_records.sys_diamond_end             --系统结束元宝
    tablerecords.begin_time = game_records.one_start_time                   --本局开始时间
    tablerecords.end_time = game_records.one_end_time                       --本局结束时间
    tablerecords.game_type = skynet.getenv("nodename")                      --游戏类型
    tablerecords.room_num = game_records.table_code                         --房间号
    local bury_landmineinfo = table_data.cur_landmineinfo
    tablerecordstr = tablerecordstr .. json.encode(tablerecords) .. "\n" 
    if bury_landmineinfo then
    	tablerecordstr = tablerecordstr .. json.encode(bury_landmineinfo) .. "\n" 
    					  .. json.encode(game_records.qhb_result) .. "\n" 
    						.. json.encode(game_records.players_balance_list)
   	else
   		tablerecordstr = tablerecordstr .. json.encode(game_records.qhb_result) .. "\n" 
    						.. json.encode(game_records.players_balance_list)
   	end

    --调用日志服务写到文件
	skynet.send(".tablerecordlog", "lua", "write", game_records.cur_record_id, tablerecordstr)
end

function tablelogic.save_table_records_nolimit(tablerecord_all, cur_landmineinfo)
	local table_data = server.table_data
	local gamename = tablelogic.get_gamename(table_data)
	local record_id = table_data.conf.uuid .. "_"
    record_id = record_id .. tablerecord_all.one_start_time .. "_"
    record_id = record_id .. tablerecord_all.one_end_time .. "_"
    record_id = record_id .. table_data.conf.play_game_type .. "_"
    record_id = record_id .. cur_landmineinfo.hb_id .. "_"
	record_id = record_id .. os.date("%Y%m%d_%H%M%S", tablerecord_all.one_start_time)
	local cur_record_id = record_id

	local sys_diamond_end = skynet.call(".slotmgr", "lua", "get_system_inventory", gamename)

	local tablerecordstr = ""
	tablerecordstr = tablerecordstr .. json.encode(tablerecord_all.conf) .. "\n"

	local tablerecords = {}
	tablerecords.user_count = tablerecord_all.user_count
	tablerecords.sys_diamond_start = tablerecord_all.sys_diamond_start
	tablerecords.sys_diamond_end = sys_diamond_end
	tablerecords.begin_time = tablerecord_all.one_start_time
	tablerecords.end_time = timetool.get_time()
	tablerecords.game_type = skynet.getenv("nodename")
	tablerecords.room_num = tablerecord_all.table_code
	tablerecordstr = tablerecordstr .. json.encode(tablerecords) .. "\n"

	tablerecordstr = tablerecordstr .. json.encode(cur_landmineinfo) .. "\n"
				.. json.encode(tablerecord_all.qhb_result) .. "\n"
					.. json.encode(tablerecord_all.players_balance_list)

	skynet.send(".tablerecordlog", "lua", "write", cur_record_id, tablerecordstr)
end

function tablelogic.standupallplayer()
	local table_data = server.table_data
	for index, seat in ipairs(table_data.seats) do
		if seat.rid ~= 0 and seat.rid ~= -1 then
			tablelogic.passive_standuptable(seat)
			---tablelogic.leavetable(seat.rid, seat)
		end
	end
end

function tablelogic.passive_standuptable(seat)
	local rids = tablelogic.getallrids()
	local ntcnotice ={
		rid = seat.rid,
	}
	server:send_notice_to_players({seat.rid}, "leavetableN", ntcnotice, nil, nil)
	---filelog.sys_error("----------leavetableN-------", ntcnotice)
	tablelogic.leavetable(seat.rid, seat)
end

function tablelogic.get_online_bury()
	local table_data = server.table_data
	local all_bury_num = #table_data.wantbury_landmineinfo
	local bury_info = nil
	local bury_seat = nil
	local enough_money = false
	repeat
		bury_info = table.remove(table_data.wantbury_landmineinfo, 1)
		if bury_info then
			bury_seat = tablelogic.get_seat_by_rid(table_data, bury_info.rid)
			if bury_seat then
				if bury_seat.diamond >= bury_info.total_money then 
					enough_money = true
				else
					local burycancelntc = { rid = bury_seat.rid }
					server:send_notice_to_players({bury_seat.rid}, "burycancelN", burycancelntc, nil, nil) 
				end
			end
		end
		all_bury_num = all_bury_num - 1
	until( (bury_info and bury_seat and enough_money) or (all_bury_num <= 0) )

	return bury_info
end

function tablelogic.get_online_bury_bynum(get_bury_landmindnum)
	local table_data = server.table_data
	local all_bury_num = #table_data.wantbury_landmineinfo
	local bury_info_alls = {}
	local bury_info = nil
	local bury_seat = nil
	local enough_money = false
	--filelog.sys_error("---------get_online_bury_bynum----", get_bury_landmindnum)
	repeat 
		bury_info = table.remove(table_data.wantbury_landmineinfo, 1)
		if bury_info then
			bury_seat = tablelogic.get_seat_by_rid(table_data, bury_info.rid)
			if bury_seat then
				if bury_seat.diamond >= bury_info.total_money then
					enough_money = true
				else
					local burycancelntc = { rid = bury_seat.rid }
					server:send_notice_to_players({bury_seat.rid}, "burycancelN", burycancelntc, nil, nil)
				end
			end
			all_bury_num = all_bury_num - 1
			if enough_money == true then
				table.insert(bury_info_alls, bury_info)
			end
		end
	until( (bury_info and #bury_info_alls >= get_bury_landmindnum) or ( all_bury_num <= 0)) 
	---filelog.sys_error("---------bury_info_alls------", bury_info_alls)
	return bury_info_alls
end



function tablelogic.get_cur_burynums()
	local table_data = server.table_data
	local all_bury_num = #table_data.wantbury_landmineinfo or 0
	return all_bury_num
end

function tablelogic.is_already_bury(rid)
	local table_data = server.table_data
	local is_buryed = false
	if not rid then return is_buryed end
	for index, buryinfo in ipairs(table_data.wantbury_landmineinfo) do
		if rid == buryinfo.rid then is_buryed = true break end
	end
	return is_buryed
end

function tablelogic.cancel_bury(rid)
	local table_data = server.table_data
	for index, buryinfo in ipairs(table_data.wantbury_landmineinfo) do
		if buryinfo.rid == rid then
			table.remove(table_data.wantbury_landmineinfo, index)
			local bury_seat = tablelogic.get_seat_by_rid(table_data, buryinfo.rid)
			if bury_seat then
				bury_seat.no_curbury_round = 0
			end
		end
	end
end

function tablelogic.check_nolimit_hbstate()
	local table_data = server.table_data
	--filelog.sys_error("---------tablelogic.check_nolimit_hbstate--------")
	if next(table_data.add_already_qhb_infos) ~= nil then
		--[[
		//座位上和游戏相关的信息，随着游戏的进行，会进行变化的，包括钻石 (抢红包玩家)
		message seat_gameinfo {
			optional int32 rid		   			= 1;
			optional int32 index	   			= 2;			//抢红包先后index
			optional int32 qiang_hb_money   	= 3;			//当前抢到的金额
			optional int32 is_landmine			= 4;			// 是否中雷
			optional int32 get_hb_money			= 5;			// 实际得到的红包的钱(中雷玩家= 抢到的红包金额 - 红包总金额)
			optional int32 balance_money		= 6;			// 实际得到的收益(扣除手续费之后)(只有玩家自己相关的时候才有值)
		}
		// 埋雷信息(发红包的相关信息)
		message bury_landmineinfo {
			optional string			hb_id 				= 1; 			//红包id(有多个红包 无限模式 使用)
			optional int32 			rid 				= 2;  			// 发红包玩家rid
			optional string 		rolename 			= 3; 			// 发红包玩家名字
			optional string 		logo 				= 4; 			//发红包玩家头像
			optional int32 			sex 				= 5; 
			optional int32 			total_money 		= 6; 			// 红包总金额
			optional int32 			left_hb_num 		= 7; 			// 剩余红包数
			optional int32			all_hb_num          = 8;            // 红包总个数
			optional int32 			landmine_num 		= 9; 			// 雷号
			optional int32 			times 				= 10;			// 倍数
			optional int32			get_money      		= 11;			// 获利多少(结算时使用)
			repeated seat_gameinfo 	qiang_hb_players 	= 12;			// 抢过该红包的玩家列表(无限模式使用 一般模式不用)
			repeated seat_gameinfo  add_qhb_players		= 13;  			// 抢红包的玩家增量列表(无限模式使用 一般模式不用)
		}
		// 红包状态更新(无限模式)
		message allhbinfoupdateN {
			repeated bury_landmineinfo 	all_hbs = 1; //
			repeated get_hb_num_list   	hb_num_lists 		= 2; 		// 枪红包数量排行
			repeated get_hb_money_list  hb_money_lists 		= 3; 		// 抢红包金额排行
		}
		--]]
		local hbinfoNdata = {
			all_hbs = {},
			hb_num_lists = {},
			hb_money_lists = {},
		}
		for hb_id, add_qhbinfo in pairs(table_data.add_already_qhb_infos) do
			local get_hb_info = tablelogic.get_can_qianghb_nolimit(hb_id)
			if get_hb_info then
				local base_landmineinfo = {
					hb_id = hb_id,
					rid = get_hb_info.rid,
					rolename = get_hb_info.rolename,
					logo = get_hb_info.logo,
					sex = get_hb_info.sex,
					total_money = get_hb_info.total_money,
					left_hb_num = get_hb_info.total_hb_num - get_hb_info.already_qhb_num,
					all_hb_num = get_hb_info.total_hb_num,
					landmine_num = get_hb_info.landmine_num,
					times = get_hb_info.times,
					get_money = 0,
					qiang_hb_players = {},
					add_qhb_players = {},
				}
				for index, qhb_playerinfo in ipairs(add_qhbinfo) do
					local base = {
						rid = qhb_playerinfo.rid,
						index = qhb_playerinfo.index,
						qiang_hb_money = qhb_playerinfo.qiang_hb_money,
						is_landmine = qhb_playerinfo.is_landmine,
						get_hb_money = qhb_playerinfo.get_hb_money,
						balance_money = qhb_playerinfo.balance_money,
					}
					table.insert(base_landmineinfo.add_qhb_players, base)
				end
				local already_qhb_playerinfo = table_data.already_qiang_landmineinfos[hb_id]
				---filelog.sys_error("------------already_qhb_playerinfo----xxxxx-------", hb_id, already_qhb_playerinfo)
				if already_qhb_playerinfo then
					for index, already_qhb in ipairs(already_qhb_playerinfo) do
						local base_data = {
							rid = already_qhb.rid,
							index = already_qhb.get_hb_index,
							qiang_hb_money = already_qhb.qiang_hb_money,
							is_landmine = already_qhb.is_landmine,
							get_hb_money = already_qhb.get_hb_money,
							balance_money = already_qhb.balance_money,
						}
						table.insert(base_landmineinfo.qiang_hb_players, base_data)
					end
				end
				table.insert(hbinfoNdata.all_hbs, base_landmineinfo)
			end
		end
		if #hbinfoNdata.all_hbs > 0 then
			--[[
			//抢红包数量排行
			message get_hb_num_list {
				optional int32 	index 		= 1;     // 排名序号
				optional int32 	rid   		= 2; 	  // 玩家rid
				optional string rolename 	= 3;	// 玩家名字
				optional string logo        = 4;    // 玩家头像
				optional int32  get_hb_num  = 5; 	// 抢红包数量
			}
			--]]
			for index, hb_num_rank in ipairs(table_data.qhb_num_rank_lists) do
				local base_data = {
					index = index,
					rid = hb_num_rank.rid,
					rolename = hb_num_rank.rolename,
					logo = hb_num_rank.logo,
					get_hb_num = hb_num_rank.get_hb_num,
				}
				table.insert(hbinfoNdata.hb_num_lists, base_data)
			end
			--[[
				//抢红包金额排行
				message get_hb_money_list {
					optional int32 	index 			= 1;     // 排名序号
					optional int32 	rid   			= 2; 	  // 玩家rid
					optional string rolename 		= 3;	// 玩家名字
					optional string logo        	= 4;    // 玩家头像
					optional int32  get_hb_money  	= 5; 	// 抢红包金额
				}
			--]]
			for index, hb_money_rank in ipairs(table_data.qhb_money_rank_lists) do
				local base_data = {
					index = index,
					rid = hb_money_rank.rid,
					rolename = hb_money_rank.rolename,
					logo = hb_money_rank.logo,
					get_hb_money = hb_money_rank.get_hb_money,
				}
				table.insert(hbinfoNdata.hb_money_lists, base_data)
			end
			local allrids = tablelogic.getallrids()
			--filelog.sys_error("-----------allhbinfoupdateN---------", hbinfoNdata)
			server:send_notice_to_players(allrids, "allhbinfoupdateN", hbinfoNdata, nil, nil)
		end
		table_data.add_already_qhb_infos = {}
	end
end

function tablelogic.is_in_rank_nolimit(rank_list, rid)
	local is_in_rank, in_index = false, 0

	for index, rank in ipairs(rank_list) do
		if rank.rid == rid then
			is_in_rank = true
			in_index = index
			break
		end
	end
	return is_in_rank, in_index
end

function tablelogic.update_qhb_num_rank(qhb_num, seatinfo)
	local table_data = server.table_data
	--[[
	//抢红包数量排行
	message get_hb_num_list {
		optional int32 	index 		= 1;     // 排名序号
		optional int32 	rid   		= 2; 	  // 玩家rid
		optional string rolename 	= 3;	// 玩家名字
		optional string logo        = 4;    // 玩家头像
		optional int32  get_hb_num  = 5; 	// 抢红包数量
	}
	--]]
	local rank_base = {
		rid = seatinfo.rid,
		rolename = seatinfo.rolename,
		logo = seatinfo.logo,
		get_hb_num = qhb_num,
	}
	local is_in_rank, in_index = tablelogic.is_in_rank_nolimit(table_data.qhb_num_rank_lists, seatinfo.rid)
	if is_in_rank == true then
		local in_data = table_data.qhb_num_rank_lists[in_index]
		if in_data then
			in_data.get_hb_num = qhb_num
			table.sort(table_data.qhb_num_rank_lists, function(first, second)
					if first.get_hb_num > second.get_hb_num then
						return true
					else
						return false
					end
			end)
		end
	else
		if #table_data.qhb_num_rank_lists < 5 then
			table.insert(table_data.qhb_num_rank_lists, rank_base)
			table.sort(table_data.qhb_num_rank_lists, function(first, second)
					if first.get_hb_num > second.get_hb_num then
						return true
					else
						return false
					end
			end)
		else
			local last_data = table_data.qhb_num_rank_lists[#table_data.qhb_num_rank_lists]
			if last_data then
				if qhb_num > last_data.get_hb_num then
					table.remove(table_data.qhb_num_rank_lists, #table_data.qhb_num_rank_lists)
					table.insert(table_data.qhb_num_rank_lists, rank_base)
					table.sort(table_data.qhb_num_rank_lists, function(first, second)
						if first.get_hb_num > second.get_hb_num then
							return true
						else
							return false
						end
					end)
				end
			end
		end
	end
end

function tablelogic.update_qhb_money_rank(qhb_money, seatinfo)
	local table_data = server.table_data
	--[[
	//抢红包金额排行
	message get_hb_money_list {
		optional int32 	index 			= 1;     // 排名序号
		optional int32 	rid   			= 2; 	  // 玩家rid
		optional string rolename 		= 3;	// 玩家名字
		optional string logo        	= 4;    // 玩家头像
		optional int32  get_hb_money  	= 5; 	// 抢红包金额
	}
	--]]
	local rank_base = {
		rid = seatinfo.rid,
		rolename = seatinfo.rolename,
		logo = seatinfo.logo,
		get_hb_money = qhb_money,
	}
	local is_in_rank, in_index = tablelogic.is_in_rank_nolimit(table_data.qhb_money_rank_lists, seatinfo.rid)
	if is_in_rank == true then
		local in_data = table_data.qhb_money_rank_lists[in_index]
		if in_data then
			in_data.get_hb_money = qhb_money
			table.sort(table_data.qhb_money_rank_lists, function(first, second)
				if first.get_hb_money > second.get_hb_money then
					return true
				else
					return false
				end
			end)
		end
	else
		if #table_data.qhb_money_rank_lists < 5 then
			table.insert(table_data.qhb_money_rank_lists, rank_base)
			table.sort(table_data.qhb_money_rank_lists, function(first, second)
				if first.get_hb_money > second.get_hb_money then
					return true
				else
					return false
				end
			end)
		else
			local last_data = table_data.qhb_money_rank_lists[#table_data.qhb_money_rank_lists]
			if last_data then
				if qhb_money > last_data.get_hb_money then
					--last_data.get_hb_money = qhb_money
					table.remove(table_data.qhb_money_rank_lists, #table_data.qhb_money_rank_lists)
					table.insert(table_data.qhb_money_rank_lists, rank_base)
					table.sort(table_data.qhb_money_rank_lists, function(first, second)
						if first.get_hb_money > second.get_hb_money then
							return true
						else
							return false
						end
					end)
				end
			end
		end
	end
end

function tablelogic.clear_player_from_ranklist(rid)
	local table_data = server.table_data
	local qhb_num_index = 0
	for index, qhb_num_rank in ipairs(table_data.qhb_num_rank_lists) do
		if qhb_num_rank.rid == rid then
			qhb_num_index = index
			break
		end
	end
	if qhb_num_index ~= 0 then
		table.remove(table_data.qhb_num_rank_lists, qhb_num_index)
	end
	local qhb_money_index = 0
	for index, qhb_money_rank in ipairs(table_data.qhb_money_rank_lists) do
		if qhb_money_rank.rid == rid then
			qhb_money_index = index
			break
		end
	end
	if qhb_money_index ~= 0 then
		table.remove(table_data.qhb_money_rank_lists, qhb_money_index)
	end
end

return tablelogic